import requests
import os

# 测试文件上传
test_file_path = 'test_data.csv'  # 准备一个测试CSV文件
if not os.path.exists(test_file_path):
    # 创建一个简单的测试CSV文件
    with open(test_file_path, 'w') as f:
        f.write("date,high_temp,low_temp\n")
        f.write("2023-01-01,15,5\n")
        f.write("2023-01-02,16,6\n")

# 测试1: 上传有效CSV文件
with open(test_file_path, 'rb') as f:
    files = {'file': (test_file_path, f, 'text/csv')}
    response = requests.post('http://localhost:5000/upload', files=files)
    print("\n测试1 - 上传有效CSV文件:")
    print("状态码:", response.status_code)
    print("响应内容:", response.json())
    assert response.status_code == 200
    assert response.json()['message'] == '文件上传成功'

# 测试2: 不上传文件
response = requests.post('http://localhost:5000/upload')
print("\n测试2 - 不上传文件:")
print("状态码:", response.status_code)
print("响应内容:", response.json())
assert response.status_code == 400
assert 'error' in response.json()

# 测试3: 上传空文件名
with open(test_file_path, 'rb') as f:
    files = {'file': ('', f, 'text/csv')}
    response = requests.post('http://localhost:5000/upload', files=files)
    print("\n测试3 - 上传空文件名:")
    print("状态码:", response.status_code)
    print("响应内容:", response.json())
    assert response.status_code == 400
    assert response.json()['error'] == '空文件名'

# 测试4: 上传非CSV文件
with open(__file__, 'rb') as f:  # 上传当前Python脚本
    files = {'file': ('test.txt', f, 'text/plain')}
    response = requests.post('http://localhost:5000/upload', files=files)
    print("\n测试4 - 上传非CSV文件:")
    print("状态码:", response.status_code)
    print("响应内容:", response.json())
    assert response.status_code == 400
    assert response.json()['error'] == '仅支持CSV文件'

# 清理测试文件
os.remove(test_file_path)
if os.path.exists('uploads/current_data.csv'):
    os.remove('uploads/current_data.csv')